<?php
declare (strict_types=1);

namespace addons\Sms\driver;

use addons\Sms\exception\SmsException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;

class Sms
{
    public function send($mobile, $content)
    {
        $uri = 'https://api.mix2.zthysms.com/v2/sendSms';
        $config = config('sms');
        $tkey = time();
        $param = [
            'tKey' => $tkey,
            'mobile' => $mobile,
            'content' => $config['sms_sign'] . $content,
            'username' => $config['sms_username'],
            'password' => md5(md5($config['sms_password']) . $tkey),
            'action' => 'send',
        ];
        try {
            $headers = [
                'Content-Type' => 'application/json',
            ];
            $res = (new Client(['verify' => false]))->request('POST', $uri, ['json' => $param, 'headers' => $headers]);

            return json_decode($res->getBody()->getContents(), true);
        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                $response = $e->getResponse();
                throw new SmsException($response->getStatusCode(), $response->getBody()->getContents());
            }
            throw $e;
        }
    }
}